package com.yanze.schoolinformation.view.community.circle;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;

import com.yanze.schoolinformation.R;
import com.yanze.schoolinformation.adapter.rv.NineImageAdapter;
import com.yanze.schoolinformation.app.AppConfig;
import com.yanze.schoolinformation.base.BaseActivity;
import com.yanze.schoolinformation.databinding.ActivityPublishDynamicBinding;
import com.yanze.schoolinformation.model.bean.ChooseImageBean;
import com.yanze.schoolinformation.model.bean.req.ReqDynamics;
import com.yanze.schoolinformation.model.bean.req.ReqSecondBook;
import com.yanze.schoolinformation.model.bean.resp.RespUser;
import com.yanze.schoolinformation.utils.ClickUtils;
import com.yanze.schoolinformation.utils.DialogUtils;
import com.yanze.schoolinformation.utils.PerfectClickListener;
import com.yanze.schoolinformation.utils.ToastUtils;
import com.yanze.schoolinformation.viewModule.circle.PublishDynamicNavigator;
import com.yanze.schoolinformation.viewModule.circle.PublishDynamicViewModel;
import com.zhihu.matisse.Matisse;

import java.util.ArrayList;
import java.util.List;

public class PublishDynamicActivity extends BaseActivity<ActivityPublishDynamicBinding> implements PublishDynamicNavigator {
    private NineImageAdapter mAdapter;
    private PublishDynamicViewModel viewModel;
    private String content;  //动态内容 | 书籍描述
    private String bookName;  //动态标题 | 书名
    private String price;  // | 价格
    private String contact;  // | 联系方式
    private String userid;
    private LocalBroadcastManager localBroadcastManager;
    private int mType;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_dynamic);
        viewModel = new PublishDynamicViewModel(this);
        viewModel.setmNavigator(this);
        mType = getIntent().getIntExtra("type", 1);
        initView();
        showContentView();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
    }

    private void initView() {
        if (mType == 1) {
            setTitle("发表动态");
            bindingView.cetContent.setHint("这一刻的想法...");
            bindingView.cetTitle.setHint("想一个标题...");
            bindingView.btnPublish.setOnClickListener(new PerfectClickListener() {
                @Override
                protected void onNoDoubleClick(View v) {
                    RespUser.UserInfo userInfo = AppConfig.getUserInfo(PublishDynamicActivity.this);
                    if (userInfo == null) {
                        ToastUtils.show("你还没有登录~");
                        return;
                    }
                    userid = userInfo.getUserid();
                    content = bindingView.cetContent.getText().toString();
                    if (content == null || content.equals("")) {
                        ToastUtils.show("内容不能为空~");
                        return;
                    }
                    upImages();
                }
            });
        }else if(mType == 2){
            bindingView.llBook.setVisibility(View.VISIBLE);
            bindingView.cetContent.setHint("书籍的描述...");
            bindingView.cetTitle.setHint("书名...");
            bindingView.cetPrice.setHint("价格...");
            bindingView.cetContact.setHint("联系方式...");
            setTitle("发布二手书");
            bindingView.btnPublish.setOnClickListener(new PerfectClickListener() {
                @Override
                protected void onNoDoubleClick(View v) {
                    RespUser.UserInfo userInfo = AppConfig.getUserInfo(PublishDynamicActivity.this);
                    if (userInfo == null) {
                        ToastUtils.show("你还没有登录~");
                        return;
                    }
                    userid = userInfo.getUserid();
                    content = bindingView.cetContent.getText().toString();
                    if (content == null || content.equals("")) {
                        ToastUtils.show("书籍描述不能为空~");
                        return;
                    }
                    bookName = bindingView.cetTitle.getText().toString();
                    if (bookName == null && bookName.equals("")) {
                        ToastUtils.show("书名不能为空~");
                        return;
                    }
                    price = bindingView.cetPrice.getText().toString();
                    if (price == null && price.equals("")) {
                        ToastUtils.show("请输入价格~~");
                        return;
                    }
                    contact = bindingView.cetContact.getText().toString();
                    if (contact == null && contact.equals("")) {
                        ToastUtils.show("请输入可以联系到你的方式~");
                        return;
                    }
                    upImages();
                }
            });
        }
        bindingView.rvImage.setLayoutManager(new GridLayoutManager(this, 4));
        mAdapter = new NineImageAdapter(this);
        mAdapter.add(new ChooseImageBean(ChooseImageBean.TYPE_ADD, null));
        bindingView.rvImage.setAdapter(mAdapter);
    }

    private void upImages() {
        List<ChooseImageBean> imagesbean = mAdapter.getData();
        List<Uri> temp = new ArrayList<>();
        for (ChooseImageBean bean : imagesbean) {
            if (bean.getType() == ChooseImageBean.TYPE_IMAGE) {
                temp.add(bean.getUri());
            }
        }
        if (temp.isEmpty()) {
            ToastUtils.show("请至少选择一张图片~");
            return;
        }
        viewModel.upImage(temp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 222 && resultCode == RESULT_OK) {
            List<Uri> select = Matisse.obtainResult(data);
            mAdapter.clear();
            for (int i = 0; i < select.size(); i++) {
                mAdapter.add(new ChooseImageBean(ChooseImageBean.TYPE_IMAGE, select.get(i)));
            }
            if (mAdapter.getItemCount() < 9) {
                mAdapter.add(new ChooseImageBean(ChooseImageBean.TYPE_ADD, null));
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onSucceed(List<String> successImage) {
        DialogUtils.showDialog(this,"正在发布...");
        if (mType == 1) {
            ReqDynamics dynamic = new ReqDynamics();
            dynamic.setTitle(bindingView.cetTitle.getText().toString());
            dynamic.setContent(content);
            dynamic.setImages(successImage);
            dynamic.setUserid(userid);
            viewModel.publicDynamic(dynamic);
        }else{
            //发布二手书信息
            ReqSecondBook secondBook = new ReqSecondBook(bookName, content, price, contact, successImage, userid);
            viewModel.publishSecondBook(secondBook);
        }
    }

    @Override
    public void onProgrees(int currnetIndex) {
        DialogUtils.showDialog(this, "正在上传第" + currnetIndex + "张图片");
    }

    @Override
    public void onFailed(int currnetIndex, String msg) {
        DialogUtils.dismissDialog();
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("提示");
        dialog.setMessage("上传第" + currnetIndex + "张图片失败：" + msg + "，是否重新上传？");
        dialog.setPositiveButton("重试", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (ClickUtils.isFastClick()) {
                    viewModel.resert();
                }
            }
        });
        dialog.setNegativeButton("取消", null);
        dialog.show();
    }

    @Override
    public void publishSuccess() {
        DialogUtils.dismissDialog();
        ToastUtils.show("发表成功");
        localBroadcastManager.sendBroadcast(new Intent("com.schoolinformation.publishdynamic"));
        finish();
    }

    @Override
    public void publishFaild(String msg) {
        ToastUtils.show(this, msg);
    }

    /**
     * 入口
     * typt 1:发布动态 2.发布二手书
     */
    public static void start(Context context,int type) {
        Intent intent = new Intent(context, PublishDynamicActivity.class);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }
}
